package org.example.linkedList;

/**
 * @Auther: wangbw
 * @Date:2020/11/19
 * @Description: org.example.linkedList
 * @version: 1.0
 */
public class Reversal2 {
    /**
     * 头插法，递归法
     * 头插法： 创建2个指针， 一个指向当前， 一个指向当前的前一个。然后用当前指向前一个， 不断循环处理
     * 递归法： 先递归，递归后将顶部的next指向次顶部。
     * @param args
     */
    public static void main(String[] args) {
        Node head = Node.createNode(5);
        Node.print(head);
        Node next = headAdd(head);
        Node.print(next);
        Node next1 = byStack(next);
        Node.print(next1);
    }

    public static Node headAdd(Node head){
        if (head == null || head.next == null)
            return head;
        Node pre = null;
        Node cur = head;
        while (cur != null){
            Node next = cur.next;
            cur.setNext(pre);
            pre = cur;
            cur = next;
        }
        return pre;
    }

    public static Node byStack(Node head){
        if (head == null || head.next == null)
            return head;
        Node temp = head.next;
        Node next = byStack(temp);
        temp.setNext(head);
        head.setNext(null);
        return next;
    }

}
